package com.security.securitydemo.base.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //可以设置内存指定的登录的账号密码,指定角色
        //不加.passwordEncoder(new MyPasswordEncoder())
        //就不是以明文的方式进行匹配，会报错  java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
        //.passwordEncoder(new MyPasswordEncoder())。
        //这样，页面提交时候，密码以明文的方式进行匹配
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("aaa").password("aaa").roles("ADMIN");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置登录,注销，表单登录不用拦截，/userIndex不拦截，其他请求要拦截,并跳转到登录页面
        http
                .authorizeRequests()
                    .antMatchers("/css/**", "/userIndex").permitAll()
                    .anyRequest().authenticated()//其他所有路径都需要权限校验
                    .and()
                    .logout().permitAll()
                    .and()
                    .formLogin()
                        .and()
                        .csrf().disable() //关闭CSRF
                        .formLogin().loginPage("/loginPage")
                        .loginProcessingUrl("/login")//form表单POST请求url提交地址，默认为/login
                        .defaultSuccessUrl("/loginSucceedController") //成功登陆后跳转页面
                        .failureUrl("/loginErrorController")
                        .permitAll();//允许所有用户都有权限访问登录页面

        //关闭默认的csrf认证
        http.csrf().disable();

    }


  /* @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .anyRequest().permitAll().and().logout().permitAll();//配置不需要登录验证
    }*/

}
